<template>
  <div>
    <div class="header-btn">
      <div>{{ title }}</div>
      <div>
        <el-button type="primary" @click="addOrUpdateTask" :loading="addLoading">确认</el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="wrap g-card" style="margin-bottom: 20px">
      <div class="title-header">基础信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="right"
        style="position: relative">
        <el-form-item label="同步动态员工" prop="syncStaff">
          <el-button class="button-new-tag" size="small" @click="openStaff">
            <svg-icon icon-class="add" /> 添加员工
          </el-button>
          <div v-if="scrmPersonSopUserRels.length > 0">
            <el-tag v-for="item in scrmPersonSopUserRels" :key="item.userId" closable @close="handleClose(item)">
              {{ item.userName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="选择客户" prop="scopeType">
          <el-radio-group v-model="form.scopeType" @change="reChooseStaff">
            <el-radio v-for="item in chooseStaffList" :key="item.label" :label="item.label" :value="item.value">{{ item.value }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.scopeType === '0'" label="客户标签" prop="customerTag">
          <div v-if="operateFlag == 'EDIT'" :key="cusIndex">
            <el-tag v-for="(item, index) in form.customerArr" :key="index">{{ item }}</el-tag>
            <svg-icon icon-class="toEdit" style="margin-left:4px" @click="toAddChange" />
          </div>
          <el-cascader v-if="operateFlag == 'ADD'" :options="tagOptions" :props="defaultprops2" v-model="form.customerTag"></el-cascader>
        </el-form-item>
      </el-form>
    </div>
    <div class="wrap g-card">
      <div class="title-header">动态内容</div>
      <el-form ref="doneForm" :model="doneForm" :rules="rules11" label-width="100px" label-position="right"
        style="position: relative">
        <el-form-item label="文本" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 3 }" placeholder="请填写文本内容" v-model="doneForm.remark" style="width: 600px" maxlength="2000" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="选择素材">
          <NormalSelectMaterial v-if="operateFlag" :selectedList="doneForm.scrmPersonSopMaterials"
            @confirmSelect="confirmSelectFn" />
        </el-form-item>
        <el-form-item label="二维码">
          <NormalQrCode v-if="operateFlag" :codeInfo="codeParams" @selectedSure="qrCodeConfrim"
            @deleteSeletedQrcode="deleteSeletedQrcode" />
        </el-form-item>
        <el-form-item label="发送类型" prop="radio">
          <el-radio-group v-model="doneForm.radio">
            <el-radio :label="'1'">立即发送</el-radio>
            <el-radio :label="'0'">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="doneForm.radio === '0'" label="选择时间" prop="date">
          <el-date-picker v-model="doneForm.date" type="datetime" placeholder="请选择时间"
            :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <!-- 修改筛选标签弹窗-->
    <el-dialog title="编辑客户标签" :visible.sync="dialogVisible" width="400px" :close-on-click-modal="false">
      <el-form label-width="90px" :rules="diaRules" ref="diaForm" :model="diaForm">
        <el-form-item label="筛选标签">
          <el-cascader :options="tagOptions" :props="defaultprops2" v-model="diaForm.customerTag"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="handleForm" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增员工弹窗 -->
    <SelectUser title="添加员工" :selectList="dialogList3" :visible.sync="staffDialog" @confirm="selectUserConfirm"
      :is-active="'1'"></SelectUser>
  </div>
</template>

<script>
import { addOrUpdateTask, editOrUpdateTask, checkOrUpdateTask, querywetaggroup, querywetagcal } from "../../../api/communityOperating/enterpriseCircle";
import SelectUser from "@/components/SelectUser/index.vue";

export default {
  name: "addDispatch",
  components: { SelectUser },
  data() {
    const remarkValidate = (rule, value, callback) => {
      const reg = /^[\w\u4E00-\u9FA5\_\-\.\:\@\#\*\/]+$/;
      if (value) {
        if (value.length > 2000) {
          callback(new Error("您录入字数超过2000字"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入文本内容"));
      }
    };
    const addValidate = (rule, value, callback) => {
      if (this.scrmPersonSopUserRels.length === 0) {
        callback(new Error("请添加员工"));
      } else {
        callback();
      }
    };
    return {
      title: "新建动态", // 页面标题
      operateFlag: '',
      codeParams: {
        qrState: '1',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: ''
      },
      // 设置不能选则当天之前的年月日和时分秒
      pickerOptions: {
        disabledDate(time) {
          var date = new Date();
          date.setFullYear(date.getFullYear() + 2);
          date.setDate(date.getDate() - 1);
          return (
            time.getTime() < Date.now() - 8.64e7 ||
            time.getTime() > date.getTime()
          );
        },
        // selectableRange: (() => {
        //   let data = new Date();
        //   let hour = data.getHours();
        //   let minute = data.getMinutes();
        //   let second = data.getSeconds();
        //   return [`${hour}:${minute}:${second} - 23:59:59`];
        // })(),
      },
      taskId: "", // 数据id
      loading: false, // 新增员工弹窗
      staffDialog: false, // 新增员工弹窗
      // 基础设置
      form: {
        taskName: "", // 任务名称
        scopeType: "1",
        remark: "",
        customerTag: [],
        customerArr: [],
        pageNum: 1,
        pageSize: 10,
      },
      // 动态设置
      doneForm: {
        remark: "",
        radio: "",
        scrmPersonSopMaterials: [], // 素材
        date: "",
      },
      tagOptions: [],
      scrmPersonSopUserRels: [], // 执行员工
      scrmPersonSopCustomerRels: [], // 选择客户
      rules: {
        syncStaff: [
          { required: true, validator: addValidate, trigger: "change" },
        ],
        scopeType: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        customerTag: [
          { required: true, message: "请选择客户标签", trigger: "change" },
        ],
      },
      rules11: {
        remark: [
          // { required: true, validator: remarkValidate, trigger: "change" },
          {maxLength: 2000, message: '您录入字数超过2000字', trigger: 'blur'}
        ],
        radio: [
          { required: true, message: "请选择发送类型", trigger: "change" },
        ],
        date: [{ required: true, message: "请选择时间", trigger: "change" }],
      },
      weekList: [], // 周期提醒
      // 选择客户
      chooseStaffList: [
        {
          label: "1",
          value: "全部客户",
          disabled: false,
        },
        {
          label: "0",
          value: "筛选客户",
          disabled: true,
        },
        // {
        //   label: "3",
        //   value: "指定客户",
        //   disabled: false,
        // },
      ],
      moId: "",
      defaultprops2: { multiple: true },
      dialogVisible: false,
      diaForm: {
        customerTag: '',
      },
      diaRules: {
        customerTag: [
          { required: true, message: "请选择客户标签", trigger: "change" },
        ],
      },
      cusIndex: 0,
      cusTagArr: '',
      addLoading: false,
      dialogList3: []
    };
  },
  created() {
    this.checkOrUpdateTask();
    // 周期
    this.getDicts("sys_sop_cycle").then((res) => {
      if (res.code === 200) {
        this.weekList = res.data;
      }
    });
  },
  methods: {
    // 初始化查询
    async checkOrUpdateTask() {
      if (this.$route.query.rowContent) {
        this.moId = this.$route.query.rowContent.moId;
        this.title = "编辑动态";
        var datas = await checkOrUpdateTask({ moId: this.moId });
        if (datas.code === 200) {
          this.doneForm.remark = datas.data.content;
          this.doneForm.scrmPersonSopMaterials = datas.data.contentDetail || [];
          this.doneForm.radio = datas.data.flagTime;
          this.doneForm.date = datas.data.pushTime;
          if (!datas.data.customerTag) {
            this.form.scopeType = '1';
          } else {
            this.form.scopeType = '0';
            this.reChooseStaff();
            this.form.customerArr = datas.data.customerArr.split(',');
            this.form.customerTag = datas.data.customerTag;
          }
          this.scrmPersonSopUserRels = datas.data.synEmplist || [];
          this.scrmPersonSopCustomerRels = datas.data.desCusList || [];
          // 回显二维码部分
          console.log(datas.data)
          if (datas.data.qrScope == 0) {
            this.codeParams = {
              qrState: 0,
              ...datas.data.qrWemoment[0]
            };
          }
        }
        this.operateFlag = 'EDIT'
      } else {
        this.title = "新建动态";
        this.operateFlag = 'ADD'
      }
    },
    // 添加
    add() {
      this.staffDialog = true;
    },
    // 选择用户
    reChooseStaff() {
      if (this.form.scopeType === "0") {
        querywetaggroup({}).then((res) => {
          this.tagOptions = res.data.children;
        });
      }
    },
    // 添加员工-打开弹窗
    openStaff() {
      this.dialogList3 = this.scrmPersonSopUserRels || []
      this.staffDialog = true;
    },
    // 删除已选人员,执行员工
    handleClose(item) {
      this.scrmPersonSopUserRels = this.scrmPersonSopUserRels.filter((x) => {
        return x.userId != item.userId;
      });
    },
    // 确认
    addOrUpdateTask() {
      let obj = {
        moId: "",
        scopeType: this.form.scopeType,
        noAddUser: "",
        customerTag: "",
        content: this.doneForm.remark,
        flag: this.doneForm.radio,
        pushTime: this.doneForm.date,
        contentType: "",
        contentDetail: null,
        qrWemoment: this.codeParams.qrState == 0 ? [this.codeParams] : null,
        qrScope: this.codeParams.qrState,
        otherContent: [],
        customerArr: [],
      };
      if (this.operateFlag == 'ADD') {
        let cusStr = '';
        let mainCusStr = '';
        if (this.form.customerTag) {
          this.form.customerTag.forEach(item => {
            cusStr += item[1] + ','
            mainCusStr += item[0] + ','
          })
        }
        cusStr = (cusStr.substring(cusStr.length - 1) == ',') ? cusStr.substring(0, cusStr.length - 1) : cusStr;
        mainCusStr = (mainCusStr.substring(mainCusStr.length - 1) == ',') ? mainCusStr.substring(0, mainCusStr.length - 1) : mainCusStr;
        obj.customerTag = cusStr || '';
        obj.customerArr = mainCusStr || '';
      } else {
        obj.customerTag = this.form.customerTag;
        obj.customerArr = this.cusTagArr || '';
      }
      let scrmPersonSopMaterials = this.doneForm.scrmPersonSopMaterials;
      if (scrmPersonSopMaterials.length > 0) {
        scrmPersonSopMaterials.forEach(item => {
          if (item.mediaType == '3') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkFile?id=' + item.id
          } else if (item.mediaType == '4') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkArticle?id=' + item.id
          } else if (item.mediaType == '10') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkForm?id=' + item.id
          }
        })
        obj.contentDetail = scrmPersonSopMaterials;
        scrmPersonSopMaterials.forEach((val, key) => {
          // 将mediaType转成字符串
          val.mediaType = String(val.mediaType);
          obj.otherContent[key] = {};
          obj.otherContent[key].other = scrmPersonSopMaterials[key].name;
          if (
            val.mediaType === "3" ||
            val.mediaType === "4" ||
            val.mediaType === "10" ||
            val.mediaType === "11"
          ) {
            // 链接
            obj.contentType = "link";
            obj.otherContent[key].mediaType = val.mediaType;
            obj.otherContent[key].annexUrl = scrmPersonSopMaterials[key].materialUrl;
            obj.otherContent[key].coverUrl = scrmPersonSopMaterials[key].coverUrl;
          } else if (val.mediaType === "5" || val.mediaType === "99") {
            // 图片
            obj.contentType = "image";
            obj.otherContent[key].mediaType = val.mediaType;
            obj.otherContent[key].content = val.content;
            obj.otherContent[key].annexUrl = scrmPersonSopMaterials[key].coverUrl;
          } else if (val.mediaType === "7") {
            // 视频
            obj.contentType = "video";
            obj.otherContent[key].mediaType = val.mediaType;
            obj.otherContent[key].content = val.content;
            obj.otherContent[key].annexUrl = scrmPersonSopMaterials[key].materialUrl;
          }
        });
      }

      // 处理员工数据
      if (this.scrmPersonSopUserRels && this.scrmPersonSopUserRels.length > 0) {
        this.scrmPersonSopUserRels.forEach((val, key) => {
          if (key + 1 < this.scrmPersonSopUserRels.length) {
            obj.noAddUser += val.userId + ",";
          } else {
            obj.noAddUser += val.userId;
          }
        });
      }
      // 处理客户数据
      if (
        this.scrmPersonSopCustomerRels &&
        this.scrmPersonSopCustomerRels.length > 0
      ) {
        this.scrmPersonSopCustomerRels.forEach((val, key) => {
          if (key + 1 < this.scrmPersonSopCustomerRels.length) {
            obj.customerTag += val.userId + ",";
          } else {
            obj.customerTag += val.userId;
          }
        });
      }
      if (
        this.$route.query.rowContent &&
        Object.keys(this.$route.query.rowContent).length > 0 &&
        this.$route.query.rowContent.moId !== ""
      ) {
        obj.moId = this.$route.query.rowContent.moId;
      }

      if (this.form.scopeType == '1') {
        obj.customerArr = '1';
        obj.customerTag = '';
      }

      this.$refs["form"].validate((valid) => {
        this.$refs["doneForm"].validate((valid11) => {
          if (valid && valid11) {
            if (+this.codeParams.qrState === 0 && !this.codeParams.activityName) {
              this.$message.error("请选择二维码！")
              return
            }
            this.addLoading = true;
            if (this.moId) {
              // 编辑
              editOrUpdateTask(obj).then((res) => {
                if (res.code === 200) {
                  this.$message.success(res.data);
                  this.$router.push({ name: "EnterpriseCircle" });
                  this.addLoading = false;
                } else {
                  this.$message.error(res.msg);
                  this.addLoading = false;
                }
              });
            } else {
              // 新增
              addOrUpdateTask(obj).then((res) => {
                if (res.code === 200) {
                  this.$message.success(res.data);
                  this.$router.push({ name: "EnterpriseCircle" });
                  this.addLoading = false;
                } else {
                  this.addLoading = false;
                  this.$message.error(res.msg);
                }
              }).catch(() => { this.addLoading = false })
            }
          } else {
            this.$message.error("您还未录入完成，请核对后提交!");
            this.addLoading = false;
          }
        });
      });
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.doneForm.scrmPersonSopMaterials = val;
    },
    // 返回
    goBack() {
      this.$router.go(-1);
    },
    //筛选弹窗
    toAddChange() {
      this.dialogVisible = true;
    },
    //筛选弹窗
    handleForm() {
      let obj = {
        moId: this.moId,
        customerTag: '',
      }
      let cusStr = '';
      let cusMainStr = '';
      if (this.diaForm.customerTag) {
        this.diaForm.customerTag.forEach(item => {
          cusStr += item[1] + ','
          cusMainStr += item[1] + ','
        })
      }
      cusStr = (cusStr.substring(cusStr.length - 1) == ',') ? cusStr.substring(0, cusStr.length - 1) : cusStr;
      cusMainStr = (cusMainStr.substring(cusMainStr.length - 1) == ',') ? cusMainStr.substring(0, cusMainStr.length - 1) : cusMainStr;
      obj.code = cusStr || '';
      this.cusTagArr = cusMainStr;
      this.$refs['diaForm'].validate(valid => {
        if (valid) {
          querywetagcal(obj).then(res => {
            if (res.code === 200) {
              this.form.customerTag = res.data.flag;
              this.form.customerArr = res.data.code.split(',');
              this.dialogVisible = false;
              this.cusIndex = this.cusIndex++;
            }
          }).catch(() => { })
        } else {
          this.$message.error('信息还没录入完成，请核对后提交！')
        }
      })

    },
    // 删除二维码
    deleteSeletedQrcode() {
      this.codeParams.qrType = '';
      this.codeParams.activityName = '';
      this.codeParams.codeUrl = '';
      this.codeParams.qrId = '';
    },
    qrCodeConfrim(data) {
      if (data) {
        this.codeParams = {
          qrState: data.qrState,
          qrType: data.qrType,
          activityName: data.activityName,
          codeUrl: data.qrCode || data.codeUrl,
          qrId: data.qrId
        }
      } else {
        this.codeParams = {
          qrState: 1,
          qrType: '',
          activityName: '',
          codeUrl: '',
          qrId: ''
        }
      }
    },

    // 弹窗的确认
    selectUserConfirm(value) {
      this.staffDialog = false
      this.scrmPersonSopUserRels = []
      value.forEach((item) => {
        this.scrmPersonSopUserRels.push({
          taskId: this.taskId,
          ...item
        })
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}
</style>
